@file:Suppress("UNUSED_PARAMETER")
package cn.mujiankeji.mbrowser.界面.标签页.网页

import android.annotation.SuppressLint
import android.widget.Space
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.功能.浏览框.模型.浏览框功能枚举
import cn.mujiankeji.mbrowser.功能.浏览框.浏览框视图
import cn.mujiankeji.mbrowser.工具.mlog
import cn.mujiankeji.mbrowser.工具.操作.地址操作
import kotlinx.coroutines.launch

const val TAG = "WebKitViewport"

/**
 * 网页标签页实现
 */
@SuppressLint("ComposableNaming", "SetJavaScriptEnabled")
@Composable
fun 网页标签实现(state: 网页标签状态) {
    // 获取浏览框
    val 浏览框 = remember(state.浏览框状态.uuid) {
        state.浏览框状态
    }
    state.coroutine = rememberCoroutineScope()
    DisposableEffect(Unit) {
        onDispose {
            state.coroutine = null
        }
    }

    LaunchedEffect(Unit) {
        state.地址.collect {
            it?.let {
                state.图标.value = 地址操作.标准化URL(地址操作.取完整主机名(it) + "/favicon.ico")
            }

        }
    }
    
    // 使用单个LaunchedEffect同步所有状态，减少协程创建和订阅数量
    LaunchedEffect(浏览框.uuid) {
        // 创建并行任务同步所有状态，避免互相阻塞
        launch {
            // 同步标题
            浏览框.标题.collect { title ->
                state.标题.value = title
            }
        }
        
        launch {
            // 同步地址
            浏览框.地址.collect { url ->
                state.地址.value = url
            }
        }
        
        launch {
            // 同步加载进度
            浏览框.加载进度.collect { progress ->
                state.加载进度.value = progress
            }
        }
        
        launch {
            // 同步前进状态
            浏览框.可否前进.collect { canGoForward ->
                state.可否前进.value = canGoForward
            }
        }
        
        launch {
            // 同步后退状态
            浏览框.可否后退.collect { canGoBack ->
                state.可否后退.value = canGoBack
            }
        }
    }

    Column(Modifier.fillMaxSize()) {
        Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars).fillMaxWidth()
            .background(if (state.头部颜色 != null) state.头部颜色!! else MaterialTheme.colorScheme.surface))
        浏览框视图(state = 浏览框)
    }

    长按菜单(state)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun 长按菜单(state : 网页标签状态){
    if (state.长按菜单列表.isNotEmpty()) {
        // 极简Material3风格底部弹窗菜单
        val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
        val scope = rememberCoroutineScope()

        ModalBottomSheet (
            onDismissRequest = { state.长按菜单列表.clear() },
            sheetState = sheetState,
            containerColor = Color.Transparent,
            dragHandle = {},
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp)
                    .padding(vertical = 8.dp)
            ) {
                @Composable
                fun item(name : String,clickable : ()->Unit){
                    Box(Modifier.fillMaxWidth()
                        .padding(vertical = 5.dp)
                        .height(45.dp)
                        .clip(MaterialTheme.shapes.medium)
                        .background(MaterialTheme.colorScheme.surface)
                        .clickable {
                            clickable()
                        },
                        contentAlignment = Alignment.Center)
                    {
                        Text(
                            text = name,
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.secondary,

                            )
                    }
                }
                state.长按菜单列表.forEachIndexed { idx, 功能 ->
                   item(功能.菜单文本()) {
                       state.执行菜单操作(item = 功能)
                       state.长按菜单列表.clear()
                   }
                }

                Spacer(Modifier.height(8.dp))

                item("取消") {
                    state.长按菜单列表.clear()
                }

                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}

// 菜单文本扩展
private fun 浏览框功能枚举.菜单文本(): String = when(this) {
    浏览框功能枚举.新窗口打开 -> "新窗口打开"
    浏览框功能枚举.打开地址 -> "打开地址"
    浏览框功能枚举.选择复制文本 -> "选择并复制文本"
    浏览框功能枚举.复制地址 -> "复制链接地址"
    浏览框功能枚举.查看图片 -> "查看图片"
    浏览框功能枚举.保存图片 -> "保存图片"
    浏览框功能枚举.复制图片地址 -> "复制图片地址"
    浏览框功能枚举.分享图片 -> "分享图片"
    浏览框功能枚举.识别二维码 -> "识别二维码"
    浏览框功能枚举.标记广告 -> "标记为广告"
    浏览框功能枚举.审查元素 -> "审查元素"
    浏览框功能枚举.查找内容 -> "查找页面内容"
}

